//
//  ZBMeViewController.m
//  ZhiBo
//
//  Created by huangtie on 2017/11/4.
//  Copyright © 2017年 huangtie. All rights reserved.
//

#import "ZBMeViewController.h"
#import "ZBMeCell.h"
#import "ZBMeInputViewController.h"
#import "SMTabBarController.h"
#import "ZBMeChanpwdViewController.h"

@interface ZBMeViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic , strong) UITableView *tableView;

@property (nonatomic , strong) NSArray <UITableViewCell *> *cells;

@property (nonatomic , strong) UIImageView *headImageView;

@property (nonatomic , strong) ZBMeCell *nickCell;
@property (nonatomic , strong) ZBMeCell *accountCell;

@property (nonatomic , assign) BOOL isReload;

@end

@implementation ZBMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的";
    
    UITableViewCell *headCell = [[UITableViewCell alloc] init];
    headCell.size = CGSizeMake(SCREEN_WIDTH, 70);
    headCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    headCell.textLabel.textColor = UICOLOR_ARGB(0xff333333);
    headCell.textLabel.font = FONT_NORMAL_14;
    headCell.textLabel.text = @"头像";
    self.headImageView = [[UIImageView alloc] init];
    self.headImageView.size = CGSizeMake(50, 50);
    self.headImageView.layer.cornerRadius = self.headImageView.width / 2;
    self.headImageView.clipsToBounds = YES;
    self.headImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.headImageView.centerY = headCell.height / 2;
    self.headImageView.right = headCell.width - 20;
    self.headImageView.backgroundColor = UICOLOR_ARGB(0xff505050);
    [headCell addSubview:self.headImageView];
    headCell.accessoryType = UITableViewCellAccessoryNone;
    headCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    self.nickCell = [[ZBMeCell alloc] init];
    self.nickCell.textLabel.text = @"昵称";
    self.nickCell.accessoryType = UITableViewCellAccessoryNone;
    self.nickCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    self.accountCell = [[ZBMeCell alloc] init];
    self.accountCell.textLabel.text = @"手机号";
    self.accountCell.accessoryType = UITableViewCellAccessoryNone;
    self.accountCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ZBMeCell *cpwdCell = [[ZBMeCell alloc] init];
    cpwdCell.textLabel.text = @"修改密码";
    cpwdCell.accessoryType = UITableViewCellAccessoryNone;
    cpwdCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
//    self.cells = @[headCell , self.nickCell , self.accountCell , cpwdCell];
    self.cells = @[headCell , self.nickCell , self.accountCell];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    self.isReload = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    WS(weakSelf)
    [[SMUserManager shareManager] cheakLogin:self callBack:^(NSString *token) {
        if (weakSelf.isReload) {
            [weakSelf requestUserInfo];
            weakSelf.isReload = NO;
        }
    } cancelBlock:^{
        SMTabBarController *tabController = (SMTabBarController *)GETWINDOW.rootViewController;
        [tabController jumpPage:SMTabBar_Code_Home];
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.isReload = YES;
}

#pragma mark REQUEST
- (void)requestUserInfo
{
    if ([[SMUserManager shareManager] isLogin]) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        WS(weakSelf)
        [SMNetwork requestOnPOST:SM_URL_GetUserInfo param:@{@"token" : [SMUserManager shareManager].token} completion:^(NSURLSessionDataTask * _Nullable task, id  _Nullable result, NSError * _Nullable error) {
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            if (!error) {
                if ([[result objectForKey:@"code"] integerValue] == 200) {
                    
                    NSDictionary *data = [result objectForKey:@"data"];
                    [SMUserManager shareManager].userInfo = [SMUser mj_objectWithKeyValues:data];
                    [weakSelf.headImageView sd_setImageWithURL:[NSURL URLWithString:[SMUserManager shareManager].userInfo.head_img]];
                    weakSelf.nickCell.contentLable.text = [SMUserManager shareManager].userInfo.nickname;
                    weakSelf.accountCell.contentLable.text = [SMUserManager shareManager].userInfo.phone;
                    
                }else{
                    [weakSelf.view makeToast:[result objectForKey:@"msg"]];
                }
            }else{
                [weakSelf.view makeToast:TIP_LOAD_FAILED];
            }
        }];
    }
}

#pragma mark DELEGATE-TABLEVIEW
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.cells.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return self.cells[indexPath.row];
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.size = CGSizeMake(SCREEN_WIDTH, 45);
    UILabel *label = [[UILabel alloc] initWithFrame:cell.bounds];
    label.textColor = UICOLOR_ARGB(0xff666666);
    label.font = FONT_NORMAL_14;
    label.text = @"退出";
    label.textAlignment = NSTextAlignmentCenter;
    [cell addSubview:label];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return self.cells[indexPath.row].height;
    }
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        return;
        switch (indexPath.row) {
            case 0:{
                UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"上传头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍一张" otherButtonTitles:@"从相册获取", nil];
                [sheet showInView:self.view];
            }
                break;
            case 1:{
                [ZBMeInputViewController launch:self defultText:@"" callback:^(NSString *text) {
                    
                }];
            }
                break;
            case 3:{
                [ZBMeChanpwdViewController launchInController:self];
            }
                break;
        }
    }else{
        [[SMUserManager shareManager] logout:^{
            SMTabBarController *tabController = (SMTabBarController *)GETWINDOW.rootViewController;
            [tabController jumpPage:SMTabBar_Code_Home];
        }];
    }
}

#pragma mark DELEGATE-ACTIONSHEET
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = YES;
    picker.delegate = self;
    if (buttonIndex == 0) {
        [SMHelper checkCameraAuthority:^(BOOL isPass) {
            if (isPass) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:picker animated:YES completion:nil];
            }
        }];
    }else if (buttonIndex == 1){
        [SMHelper checkPhotoAuthority:^(BOOL isPass) {
            if (isPass) {
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:picker animated:YES completion:nil];
            }
        }];
    }
}

#pragma mark DELEGATE-IMAGEPICKER
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [UIApplication sharedApplication].statusBarHidden = NO;
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqual:@"public.image"]) {
//        UIImage *originImage = [info objectForKey:UIImagePickerControllerEditedImage];
//        __block NSData *data = UIImageJPEGRepresentation(originImage, 0.5);
        //上传图片
//        WS(weak);
//        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        [SMNetwork requestOnUpload:DI_URL_CHANGEAVATAR param:[NSDictionary dictionary] datas:@[data] completion:^(NSURLSessionDataTask * _Nullable task, id  _Nullable result, NSError * _Nullable error) {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            if (!error) {
//                if ([[result objectForKey:@"errorCode"] integerValue] == 0) {
//                    //更新用户数据
//                    [[SMUserManager shareManager] reloadUserInformation:nil];
//                    [weak.view makeToast:@"上传成功"];
//                }else{
//                    [weak.view makeToast:[result objectForKey:@"errorMsg"]];
//                }
//            }else{
//                [weak.view makeToast:TIP_LOAD_FAILED];
//            }
//        }];
//
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}



@end
